import { queryList } from '@/api/modules/sysDictionaryEnco'

export function useMixinQueryIndicatorDicts() {
  const [indicatorDicts, setIndicatorDicts] = useShallowState<any[]>([])
  const [indicatorDictsWithKey, setIndicatorDictsWithKey] = useShallowState<any[]>([])
  async function getIndicatorDicts() {
    try {
      const { data } = await queryList('INDICATOR_NAME_TABLE')
      setIndicatorDictsWithKey(
        (data || []).map((v: any) => {
          return {
            key: v.dicKey,
            value: v.dicValue,
          }
        }),
      )
      setIndicatorDicts(
        (data || []).map((v: any) => v.dicValue),
      )
    }
    catch (e) {
      console.warn(e)
    }
  }

  function getKeyFromValue(value: string): string | null {
    const array = unref(indicatorDictsWithKey)
    for (let i = 0; i < array.length; i++) {
      if (array[i].value === value) {
        return array[i].key
      }
    }
    return null
  }

  function getValueFromKey(key: string): string | null {
    const array = unref(indicatorDictsWithKey)
    for (let i = 0; i < array.length; i++) {
      if (array[i].key === key) {
        return array[i].value
      }
    }
    return null
  }

  function isInternalIndicator(value: string): boolean {
    return unref(indicatorDictsWithKey).some((v: any) => v.value === value)
  }

  return {
    indicatorDicts,
    indicatorDictsWithKey,
    getIndicatorDicts,
    /** 根据指标名称value获取对应的key */
    getKeyFromValue,
    /** 根据指标名称key获取对应的value */
    getValueFromKey,
    /** 判断是否为内置指标 */
    isInternalIndicator,
  }
}
